import React, { Component, Fragment } from 'react';
import { List, InputItem, NavBar, Popover, Icon, Grid } from 'antd-mobile';
import { connect } from 'dva';
import { routerRedux } from 'dva/router';
import io from 'socket.io-client';
import { parse as qsParse } from 'qs';
import { emojiArr } from '../../assets/emoji';
import styles from './index.css';
const ChatItem = List.Item;
const Item = Popover.Item;
const formatEmojiArr = emojiArr.map((item) => ({
  text: item,
}));
class ChatMessage extends Component {
  constructor(props) {
    super(props);
    this.state = {
      msgVal: '',
      maskVisible: false,
      showExpress: false
    }
  }
  componentDidMount () {
    this.socket = io('https://118.25.208.36', { secure: true, transports: ['websocket'], rejectUnauthorized: false  });
    // this.socket = io('http://localhost:3333');
    window.socket = this.socket;
    this.socket.on('connect', () => {
      console.log('client连接成功');
    });
    this.socket.on('receiveChatMsg', data => {
      console.log('client', data);
      // 更新被发送者聊天数据
      this.getChatMsgList();
    });
    this.socket.on('disconnect', () => { console.log('client连接失败') });
    this.getSendedUser();
    this.getChatMsgList();
  }
  UNSAFE_componentWillReceiveProps (nextProps) {
    console.log(666, nextProps.userInfo)
  }
  componentWillUnmount() {
    clearTimeout(this.timeout);
  }
  handleSelect () {
    this.setState({ maskVisible: false });
  }
  handleInput (val) {
    this.setState({ msgVal: val });
  }
  getSendedUser () {
    // 获取
    const { location, dispatch } = this.props;
    const toUserId = qsParse(location.search.substr(1)).toUserId;
    dispatch({
      type: 'user/getSendedUserInfo',
      payload: {
        sendedId: toUserId
      }
    });
  }
  getChatMsgList = () => {
    const { dispatch, userInfo, location } = this.props;
    const toUserId = qsParse(location.search.substr(1)).toUserId;
    dispatch({
      type: 'chat/getChatList',
      payload: {
        toUserId,
        fromUserId: userInfo._id
      }
    })
  }
  handleExpress = (el) => {
    const { msgVal } = this.state;
    this.setState({ msgVal: `${msgVal}${el.text}` });
  }
  handleSend () {
    const { msgVal } = this.state;
    const { location, userInfo, dispatch } = this.props;
    const toUserId = qsParse(location.search.substr(1)).toUserId;
    const { _id: fromUserId } = userInfo;
    // 更新当前用户发送消息的列表数据
    dispatch({
      type: 'chat/saveChatMsg',
      payload: {
        toUserId,
        fromUserId,
        chatMsgVal: msgVal
      },
      cb: () => {
        this.socket.emit('sendChatMsg');
        this.setState({ msgVal: '', showExpress: false });
      }
    });
  }
  renderChatMsgList () {
    const { sendedUserInfo, userInfo: { _id, avatar: userAvatar }, chatList } = this.props;
    const { avatar: sendedAvatar } = sendedUserInfo;
    return chatList.map((item, index) => {
      if (item.toUserId === _id) {
        return (
          <List>
            <ChatItem wrap key={String(index)} thumb={sendedAvatar}>{ item.chatMsgVal }</ChatItem>
          </List>
        )
      }
      return (
        <List>
          <ChatItem wrap key={String(index)} extra={<img src={userAvatar} />}>{ item.chatMsgVal }</ChatItem>
        </List>
      )
    })
  }
  toggleExpress = () => {
    const { showExpress } = this.state;
    this.setState({ showExpress: !showExpress }, () => {
      this.timeout = setTimeout(() => {
        window.dispatchEvent(new Event('resize'));
      }, 0);
    });
  }
  renderSendBox = () => {
    return (
      <Fragment>
        <span className={styles.sendBtn} onClick={this.toggleExpress}>表情</span>
        <span style={{ borderLeft: '1px solid #bbb', margin: '0 5px' }}></span>
        <span className={styles.sendBtn} onClick={this.handleSend.bind(this)}>发送</span>
      </Fragment>
    )
  }
  render() {
    const { sendedUserInfo, dispatch } = this.props;
    const { msgVal, maskVisible, showExpress } = this.state;
    return (
      <div className={styles.chatBox}>
        <div>
          <NavBar
            type="dark"
            leftContent="返回"
            onLeftClick={() => { dispatch(routerRedux.goBack()) }}
            rightContent={
              <Popover
                overlayClassName="fortest"
                overlayStyle={{ color: 'currentColor' }}
                visible={maskVisible}
                overlay={[
                  (<Item style={{ backgroundColor: '#108ee9', color: '#fff' }} key="cleanChatMsg" value="cleanChatMsg">清空聊天记录</Item>),
                ]}
                align={{
                  overflow: { adjustY: 0, adjustX: 0 },
                  offset: [-10, 0],
                }}
                onSelect={this.handleSelect.bind(this)}
              >
                <div style={{
                  height: '100%',
                  padding: '0 15px',
                  marginRight: '-15px',
                  display: 'flex',
                  alignItems: 'center',
                }}
                >
                  <Icon type="ellipsis" onClick={() => {this.setState({ maskVisible: true })}} />
                </div>
              </Popover>
            }
          >{ sendedUserInfo.userName }</NavBar>
          { this.renderChatMsgList() }
        </div>
        <List>
          <InputItem
            placeholder="请输入发送内容"
            value={msgVal}
            onChange={this.handleInput.bind(this)}
            extra={this.renderSendBox()}
          ></InputItem>
          {
            showExpress && <Grid data={formatEmojiArr} columnNum={6} carouselMaxRow={3} isCarousel onClick={this.handleExpress} />
          }
        </List>
      </div>
    )
  }
}
function mapStateToProps ({ user, chat }) {
  const { userInfo, sendedUserInfo } = user;
  const { chatList } = chat;
  return { userInfo, sendedUserInfo, chatList };
};
export default connect(mapStateToProps)(ChatMessage);